﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TCP_Spy
{
    public partial class Form1 : Form
    {

        SynchronizationContext sync1 = null;
        SynchronizationContext sync2 = null;

        Form2 Form2obj = new Form2();

        public Form1()
        {
            InitializeComponent();
            sync1 = SynchronizationContext.Current;
            sync2 = SynchronizationContext.Current;
            startThread();
            startThread_update();
        }

        Thread th1 = null;
        Thread th2 = null;

        void startThread() // 线程启动函数
        {
            th1 = new Thread(myReceive);
            th1.Start();
        }

        void myReceive() // 线程函数
        {
            while (true)
            {
                Thread.Sleep(100);
                if (Socket_Class.socket_stat)
                {
                    sync1.Post(updateText, Socket_Class.Receive());
                }
                sync1.Post(Disconnect_test, null);
            }
        }

        void updateText(object obj)
        {
            richTextBox_接收.AppendText(obj.ToString() + "\r\n");
            this.richTextBox_接收.SelectionStart = this.richTextBox_接收.Text.Length;
            this.richTextBox_接收.ScrollToCaret();
        }

        void Disconnect_test(object obj)
        {
            if (Socket_Class.socket_close_judge)
            {
                Socket_Class.socket_close_judge = false;
                Socket_Class.socket_stat = false;
                Form2obj.label_状态.Text = "未连接";
                Form2obj.button_连接.Text = "连接";
            }
        }

        void startThread_update() // 线程启动函数
        {
            th2 = new Thread(my_update);
            th2.Start();
        }

        void my_update()
        {
            while (true)
            {
                if (label_连接.Text != Form2obj.label_状态.Text)
                    sync2.Post(update_stat_Text, null);
            }
        }

        void update_stat_Text(object obj)
        {
            label_连接.Text = Form2obj.label_状态.Text;
        }

        private void button_发送_Click(object sender, EventArgs e)
        {
            string Socket_send = richTextBox_发送.Text;
            if (Socket_Class.socket_stat)
            {
                if (Socket_send != "")
                    Socket_Class.Send(Socket_send);// 向服务器发送数据
            }
        }

        private void button_退出_Click(object sender, EventArgs e)
        {
            Socket_Class.socket_close();
            System.Environment.Exit(0);
        }

        private void toolStripMenuItem_设置_Click(object sender, EventArgs e)
        {
            Form2obj.Show();
        }
    }
}
